package edu.hawaii.duedates.libraries;

import java.util.List;
import java.util.ArrayList;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;
import edu.hawaii.duedates.BorrowedItem;
import edu.hawaii.duedates.LenderQuery;

/**
 * Uh Manoa class.
 * 
 * @author Daniel Tian
 * @author Aric West
 */
public class UhManoaLibraryQuery extends LenderQuery {
  private String id;
  private String lastName;
  private final int numOfFields;
  private final String libraryName;

  /**
   * Constructor.
   */
  public UhManoaLibraryQuery() {
    numOfFields = 2;
    libraryName = "University of Hawaii at Manoa";
  }

  /**
   * Returns the number of expected fields for this class.
   * 
   * @return The number of expected fields
   */
  public int getExpectedFieldLength() {
    return numOfFields;
  }

  /**
   * Returns the library name.
   * 
   * @return the library name
   */
  public String getLenderName() {
    return libraryName;
  }

  /**
   * Sets the fields required by this class to log in.
   * 
   * @param fieldList the list of fields that this class needs
   * @throws Exception thrown if number of fields received is not the same as the number expected
   */
  public void setFields(List<String> fieldList) throws Exception {
    if (fieldList.size() == numOfFields) {
      this.id = fieldList.get(0);
      this.lastName = fieldList.get(1);
    }
    else {
      throw new Exception("Expected " + numOfFields + "fields passed, received "
          + fieldList.size());
    }
  }

  /**
   * Attempts to login to UH Manoa Library system. Code modified from
   * Philip Johnson's bootstrap code available here:
   * 
   * http://groups.google.com/group/ics-software-engineering-fall-2008/
   * web/DueDateBootstrap-1.0.1010.zip
   * 
   * @return The WebConversation instance after successful login.
   * @throws Exception If login was not successful with these credentials.
   */
  public WebConversation logIn() throws Exception {
    String url = "http://uhmanoa.lib.hawaii.edu/cgi-bin/Pwebrecon.cgi?DB=local&PAGE=pbLogon";

    // UH Library website has bogus JavaScript code.
    HttpUnitOptions.setExceptionsThrownOnScriptError(false);

    // create the conversation object which will maintain state for us
    WebConversation conversation = new WebConversation();
    WebRequest request = new GetMethodWebRequest(url);
    WebResponse response = conversation.getResponse(request);
    WebForm form = response.getFormWithName("logonpage");

    form.setParameter("BC", this.id);
    form.setParameter("LN", this.lastName);
    form.submit();
    response = conversation.getCurrentPage();

    if (response.getText().contains("Sorry, Login unsuccessful")) {
      throw new Exception("Error while logging in to UH Library");
    }

    return conversation;
  }

  /**
   * Given a logged in user to the UH Library site, provides info about their library books.
   * Code modified from Philip Johnson's bootstrap code available here:
   * 
   * http://groups.google.com/group/ics-software-engineering-fall-2008/
   * web/DueDateBootstrap-1.0.1010.zip
   * 
   * @return A String containing information about their books.
   * @throws Exception If problems occur parsing the site pages.
   * 
   */
  public List<BorrowedItem> getBorrowedItems() throws Exception {
    String uhSiteNoItemString = "You have no items checked out.";

    try {
      WebConversation conversation = this.logIn();
      WebResponse response = conversation.getCurrentPage();
      WebForm form = response.getForms()[0];

      List<BorrowedItem> itemList = new ArrayList<BorrowedItem>();

      if (!uhSiteNoItemString.equals(form.getText())) {
        // Assume the first table is the one we need. Not true in general.
        WebTable table = response.getTables()[0];

        for (int i = 1; i < table.getRowCount(); i++) {
          itemList.add(new BorrowedItem(table.getCellAsText(i, 1), table.getCellAsText(i, 3)));
        }
      }

      return itemList;
    }
    catch (Exception e) {
      throw new Exception("Error getting UH Book info", e);
    }
  }
}
